import {casConfig} from './config';
import {cookie} from '@yjtec/cas-cookie';
import {getUrlQuery}  from './utils/utils';
import query from './service';
import event from './events';
export default async function(){
  let re = await checkCookieTicket();
  if(re){ //存在cookie
    return re;
  }else{ //不存在cookie
    const re = await checkUrlTicket();
    if(re){
      return re;
    }else{
      event.emit('cas.nologin');
      return Promise.resolve(false);
    }
  }
}

export async function checkCookieTicket(){
  alert(1212);
  let cookieTicket = getCookieTicket();
  if(cookieTicket){
    const re = await checkTicket(cookieTicket);
    if(re){ //ticket合法
      event.emit('cas.check.success',{
        ticket:cookieTicket,
        user:re
      })
      return Promise.resolve({
        ticket:cookieTicket,
        user:re
      });
    }else{ //tiket不合法
      event.emit('cas.check.error',{
        ticket:cookieTicket
      });
      return Promise.resolve(false);
    }
  }else{
    return Promise.resolve(false);
  }
}
export async function checkUrlTicket(){
  let urlTicket = getUrlTicket();
  if(urlTicket){ //url存在ticket
    const re = await checkTicket(urlTicket);
    if(re){ //ticket合法
      event.emit('cas.login.success',{
        ticket:urlTicket,
        user:re
      })
      return Promise.resolve({
        ticket:urlTicket,
        user:re
      });
    }else{ //tiket不合法
      event.emit('cas.login.error',{
        ticket:urlTicket
      });
      return Promise.resolve(false);
    }
  }else{ //url不存在ticket
    //event.emit('cas.nologin');
    return Promise.resolve(false);
  }
}
export async function checkTicket(ticket){
  let uri = casConfig.get('action');
  const re = await query(uri,ticket);
  if(re.errcode == 0 && re.data){
    return re.data;
  }else{
    return false;
  }
}

export function getCookieTicket() {
  return cookie.getCookie();
}

export function getUrlTicket(){
  return getUrlQuery(window.location.href,'ticket');
}